class CustomersController < ApplicationController
  before_filter :authorize
  # GET /customers
  # GET /customers.xml
  def index
    if admin?
      @customers = Customer.find :all
    else
      @customers = Customer.find :all, :conditions => ["user = ?", cur_user.name]
    end  

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @customers }
    end
  end

  # GET /customers/1
  # GET /customers/1.xml
  def show
    @customer = Customer.find(params[:id])
    if check? @customer
      respond_to do |format|
        format.html # show.html.erb
        format.xml  { render :xml => @customer }
      end
    else
      need_admin
    end
  end

  # GET /customers/new
  # GET /customers/new.xml
  def new
    @customer = Customer.new    
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @customer }
    end
  end

  # GET /customers/1/edit
  def edit
    @customer = Customer.find(params[:id])
    check? @customer 
  end

  # POST /customers
  # POST /customers.xml
  def create
    @customer = Customer.new(params[:customer])
    @customer.user = cur_user.name unless @customer.user
    
    if check? @customer
      respond_to do |format|
        if @customer.save
          flash[:notice] = '客户信息保存成功.'
          format.html { redirect_to(@customer) }
          format.xml  { render :xml => @customer, :status => :created, :location => @customer }
        else
          format.html { render :action => "new" }
          format.xml  { render :xml => @customer.errors, :status => :unprocessable_entity }
        end
      end
    else
      need_admin
    end
  end

  # PUT /customers/1
  # PUT /customers/1.xml
  def update
    @customer = Customer.find(params[:id])
    if check? @customer 
      respond_to do |format|
        if @customer.update_attributes(params[:customer])
          flash[:notice] = '客户信息更新成功.'
          format.html { redirect_to(@customer) }
          format.xml  { head :ok }
        else
          format.html { render :action => "edit" }
          format.xml  { render :xml => @customer.errors, :status => :unprocessable_entity }
        end
      end
    else
      need_admin
    end
  end
  
  # DELETE /customers/1
  # DELETE /customers/1.xml
  def destroy
    @customer = Customer.find(params[:id])
    if check? @customer 
      @customer.destroy
      respond_to do |format|
        format.html { redirect_to(customers_url) }
        format.xml  { head :ok }
      end
    else
      need_admin
    end
  end
  
  private
  def check? cust
    u = cur_user
    if u.admin? || u.name == cust.user
      true
    else
      false
    end    
  end
end
